package org.victoria.csms.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.victoria.common.controller.BaseController;
import org.victoria.common.domain.Page;
import org.victoria.common.utils.QueryHelper;
import org.victoria.common.utils.ResponseUtil;
import org.victoria.common.utils.StringUtils;
import org.victoria.csms.domain.*;
import org.victoria.csms.service.*;
//import org.victoria.csms.service.imp.GoodsStorageServiceImp;
import org.victoria.csms.util.NumberUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Greyson on 2015/6/9.
 */
@Controller
public class StorageOutController  extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StorageController.class);

    @Autowired
    private StorageOutDetailService storageOutDetailService;
    @Autowired
    private StorageOutService storageOutService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsStorageService goodsStorageService;

    @RequestMapping(value = "/admin/stock/addStorageOut.htm", method = RequestMethod.POST)
    public String addStorageOut(StorageOut storageOut, Long storeRoom, Date storageOutDateTimeStr){
        storageOut.setStorageOutDateTime(storageOutDateTimeStr);
        System.out.println("addStorageOut's date: " + storageOut.getStorageOutDateTime());
        System.out.println("addStorageOut's room: " + storeRoom);

        Storage storage = new Storage();
        storage.setId(storeRoom);
        storageOut.setStorage(storage);
        storageOutService.saveEntity(storageOut);
        return "redirect:/ admin/stock/showStorageOut.htm";
    }

    @RequestMapping(value = "/admin/stock/showStorageOut.htm")
    public String showStorageOut(Model model, Integer pageNum, String storageID, String storageOutID, String startTime, String endTime, String storageOutNumber){
        pageNum = pageNum == null ? 1 : pageNum;
        Page<StorageOut> page = storageOutService.getList(pageNum, storageID, storageOutNumber, startTime, endTime);
        model.addAttribute(page);
        for(StorageOut data : page.getRecordList()){
            Storage s = data.getStorage();
            System.out.println("storage: "+s.getSto_number()+" - "+s.getSto_name()+" - "+s.getConnect_man());
        }
        List<Storage> storageList = storageService.getAll();
        model.addAttribute("storageList", storageList);
        model.addAttribute("storageID", storageID);
        model.addAttribute("storageOutNumber", storageOutNumber);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        return "admin/stock/storageOut";
    }

    @RequestMapping(value = "/admin/stock/deleteStorageOut.htm")
    public void deleteStorageOut(HttpServletResponse response, Long storageOutID){
        JSONObject object = ResponseUtil.getJsonObject();
        if (storageOutID == null){
            object.put("code", 1);
            object.put("message", "The parameter had mistake");
            ResponseUtil.renderJson(response, object.toJSONString());
        }
        storageOutService.deleteById(storageOutID);
        object.put("code",0);
        object.put("message", "delete successful");
        ResponseUtil.renderJson(response, object.toJSONString());
    }

    @RequestMapping(value = "/admin/stock/storageOutAdd.htm")
    public String storageOutAdd(Model model){
        List<Storage> storageList = storageService.getAll();
        model.addAttribute("storageList", storageList);

        System.out.println("storageOutAdd: "+storageList);
        model.addAttribute("storageOutNumber", NumberUtil.getOrderNumber("RC"));
//      System.out.println("storageOutAdd: "+storageOutNum);
        return "/admin/stock/orderOutAdd";
    }

    public String updateStorageOut(){
        return "";
    }

    @RequestMapping(value = "/admin/stock/storageOutDetail.htm")
    public String showStorageOutDetail(Model model, Long storageOutID, Integer pageNum){
        System.out.println("showStorageDetail: " + storageOutID);
        StorageOut storageOut = storageOutService.getById(storageOutID);
        model.addAttribute("storageOut", storageOut);

        pageNum = pageNum == null ? 1 : pageNum;
        Page<StorageOutDetail> page = storageOutDetailService.getList(pageNum, storageOut.getStorageOutID().toString());
        model.addAttribute(page);
        System.out.println("showStorageOutDetai's page: " + page.getRecordList());
        return "/admin/stock/storageOutDetail";
    }

    @RequestMapping(value = "/admin/stock/storageOutDetailAdd.htm")
    public String storageOutDetailAdd(Model model, Long storageID, Long storageOutID){
        List<Goods> goodsList = goodsService.getAll();
        List<List<Object>> sumList = new ArrayList<List<Object>>();
        Goods_Storage gs = null;
        for(Goods goods : goodsList){
            gs = goodsStorageService.getByGoodsStorageID(goods.getGoodsID(), storageID);
            if(gs != null){
//                Map<String, Goods> map = new HashMap<String, Goods>();
                List list2 = new ArrayList();
                list2.add(gs.getStorageSum());
                list2.add(goods);
//                map.put(gs.getStorageSum(), goods);
                sumList.add(list2);
            }
        }
//        for(int i=0; i<goodsList.size(); i++){
//            for(Goods_Storage gs : goodsList.get(i).getGoods_storages()){
//                if(gs.getStorage().getId() == storageID){
//                    sumList.add(gs.getStorageSum());
//                    System.out.println("storageOutDetail's storageNum of "+i+" is: "+sumList.get(i));
//                }else{
//                    sumList.add("");
//                }
//            }
//        }
        System.out.println("storageOutDetailAdd: " + storageOutID + " -+- " + storageID+" -+- "+sumList.size()+" -+- "+goodsList.size());
        model.addAttribute("storageOutID", storageOutID);
        model.addAttribute("storageID", storageID);
        model.addAttribute("sumList", sumList);
        model.addAttribute(goodsList);

//        goodsStorageService.getByGoodsStorageID(String goodsID, String storageID);
        return "/admin/stock/orderOutDetailAdd";
    }

    @RequestMapping(value = "/admin/stock/addStorageOutDetail.htm")
    public String addStorageOutDetail(Model model, int storageOutCount, String goodsInfo, Long storageID, Long storageOutID){
        System.out.println("addStorageOutDetail's storageID: " + goodsInfo + " and the storageID is: " + storageID+" -- "+storageOutID);
        String goodsID = goodsInfo.split("\\*")[0];
        System.out.println("goodsIfDo: "+goodsID);
//        Storage storage = storageService.getById(storageID);

        //update the number of the goods in a specific storage
        Goods_Storage gs = goodsStorageService.getByGoodsStorageID(Long.parseLong(goodsID), storageID);
        Goods goods = goodsService.getById(Long.parseLong(goodsID));
        int regionNum = Integer.parseInt(gs.getStorageSum());
        if(storageOutCount <= regionNum){
            gs.setStorageSum(String.valueOf(regionNum - storageOutCount));
            goodsStorageService.updateEntity(gs);
        }

//        Set<Goods_Storage> set = new HashSet<Goods_Storage>();
//        set.add(gs);
//        storage.setGoods_storages(set);
//        storageService.updateEntity(storage);

        //save a data of StorageOut
        StorageOut so = storageOutService.getById(storageOutID);
        StorageOutDetail detail = new StorageOutDetail();
        detail.setStorageOut(so);
        detail.setGoods(goods);
        detail.setGoodsNumber(storageOutCount);
        storageOutDetailService.saveEntity(detail);
        return "redirect:/ admin/stock/storageOutDetail.htm?storageOutID="+storageOutID;
    }

    @RequestMapping(value = "/admin/stock/deleteStorageOutDetail.htm")
    public void deleteStorageOutDetail(HttpServletResponse response,Long storageOutDetailID){
        System.out.println("deleteStorageOutDetail: "+storageOutDetailID);
        JSONObject object = ResponseUtil.getJsonObject();
        if (storageOutDetailID == null){
            object.put("code", 1);
            object.put("message", "The parameter had mistake");
            ResponseUtil.renderJson(response, object.toJSONString());
        }
        storageOutDetailService.deleteById(storageOutDetailID);
        object.put("code",0);
        object.put("message", "delete successful");
        ResponseUtil.renderJson(response, object.toJSONString());
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyy-MM-dd"), true));
    }
}
